package org.itboys.mobile.controller;
import org.apache.ibatis.annotations.Param;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.mobile.entity.mysql.wallet.PearlWalletWithdrawRecord;
import org.itboys.mobile.service.mysql.mobile.wallet.PearlWalletService;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.score.SundayMemberFinanceDto;
import org.itboys.mobile.service.mongo.mobile.SundayMobileMemberService;

import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

    /**
     * Created on 2017/9/26.
     * @author 朱坤涛
     */
    @Controller
    @RequestMapping("/pearl/mobile/wallet")
    public class PearlMobileWalletController extends BaseController {
        @Autowired
        private PearlWalletService walletService;
        @Autowired
        private SundayMobileMemberService memberService;

        /**
         * 【用户版和管理版】钱包，获取钱余额。不分页
         */

        public void getRevenue(HttpServletRequest request, HttpServletResponse response,
                               @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                               @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
        ) {
            try {
                Long memberId = AccountIdHoldUtils.getMemberId();
                SundayMemberFinanceDto financeDto = memberService.getMemberFinance(memberId, null);
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("totalRevenue", financeDto.getBalance());
                result.put("ableRevenue", financeDto.getBalance());
                result.put("frozenRevenue", new BigDecimal("0"));
                result.put("info", "totalRevenue(总余额，暂不适用)，ableRevenue（可用余额），frozenRevenue（冻结余额，暂不适用）");
                ResponseMessage.success(result);
            } catch (Exception e) {
                String msg = CommonConstants.ERROMSG;
                Integer code = CommonConstants.FAIL_CODE;
                //自定义异常（签名错误）
                if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                    msg = e.getMessage();
                    //token已过期
                } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                    code = CommonConstants.TOKEN_CODE;
                    msg = CommonConstants.TOKENMSG;
                } else {
                    logger.error("/pearl/mobile/wallet/getRevenue----e=" + e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code, msg);
            }

        }

        /**
         * 获取交易记录
         */
        @RequestMapping(value = "/record/select", method = RequestMethod.POST)
        @ApiOperation(value = "【用户版和管理版】钱包（收益）获取交易记录。分页")
        public void record_select(HttpServletRequest request,
                                  HttpServletResponse response,
                                  // @ApiParam(required = true, name = "memberId", value = "用户ID") @RequestParam(value="memberId",required=true) Long memberId,
                                  @ApiParam(required = false, name = "type", value = "查询参数。交易类型。1，充值，2，充值赠送，3，消费抵扣，4系统返还") @RequestParam(value = "type", required = false) Integer type,
                                  @ApiParam(required = false, name = "remark", value = "查询参数。交易备注。") @RequestParam(value = "remark", required = false) String remark,

                                  @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                                  @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                                  @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                                  @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                                  @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                                  @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
        ) {
            try {
                Long memberId = AccountIdHoldUtils.getMemberId();
                List<Map<String, Object>> result = walletService.getRecords(request, memberId);
                ResponseMessage.success(result);
            } catch (Exception e) {
                String msg = CommonConstants.ERROMSG;
                Integer code = CommonConstants.FAIL_CODE;
                //自定义异常（签名错误）
                if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                    msg = e.getMessage();
                    //token已过期
                } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                    code = CommonConstants.TOKEN_CODE;
                    msg = CommonConstants.TOKENMSG;
                } else {
                    logger.error("/pearl/mobile/wallet/record/select----e=" + e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code, msg);
            }
        }

        /**
         * 【用户版和管理版】钱包，获取充值产品。不分页
         */

        @RequestMapping(value = "/product/select", method = RequestMethod.POST)
        @ApiOperation(value = "【用户版和管理版】钱包，获取充值产品。不分页")
        public void product_select(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                                   @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
        ) {
            try {
                Long memberId = AccountIdHoldUtils.getMemberId();
                List<Map<String, Object>> result = walletService.getProduct(memberId);
                ResponseMessage.success(result);
            } catch (Exception e) {
                String msg = CommonConstants.ERROMSG;
                Integer code = CommonConstants.FAIL_CODE;
                //自定义异常（签名错误）
                if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                    msg = e.getMessage();
                    //token已过期
                } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                    code = CommonConstants.TOKEN_CODE;
                    msg = CommonConstants.TOKENMSG;
                } else {
                    logger.error("/kitchen/mobile/income/product/select----e=" + e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code, msg);
            }
        }


        /**
         * 【用户版和管理版】钱包-充值-创建订单。单次只能购买一个充值产品
         */

        @RequestMapping(value = "/product/createOrder", method = RequestMethod.POST)
        @ApiOperation(value = "【用户版和管理版】钱包-充值-创建订单。单次只能购买一个充值产品")
        public void product_createOrder(HttpServletRequest request,
                                        HttpServletResponse response,
                                        @ApiParam(required = true, name = "productId", value = "充值产品Id") @RequestParam(value = "productId", required = true) Long productId,
                                        @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                                        @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
        ) {
            try {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("productId", productId);
                param.put("nonce", nonce);
                param.put("sign", sign);
                Long memberId = AccountIdHoldUtils.getMemberId();
                Map<String, Object> result = walletService.createOrder(memberId, productId);
                ResponseMessage.success(result);
            } catch (Exception e) {
                String msg = CommonConstants.ERROMSG;
                Integer code = CommonConstants.FAIL_CODE;
                //自定义异常（签名错误）
                if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                    msg = e.getMessage();
                    //token已过期
                } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                    code = CommonConstants.TOKEN_CODE;
                    msg = CommonConstants.TOKENMSG;
                } else {
                    logger.error("/kitchen/mobile/income/product/createOrder----e=" + e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code, msg);
            }
        }

        /**
         * 申请提现
         */
        @RequestMapping(value = "/applyWithdraw",method = RequestMethod.POST)
        @ApiOperation(value = "【用户版和管理版】钱包余额提现申请。")
        public void applyWithdraw(
                HttpServletRequest request,
                HttpServletResponse response,
                @RequestParam(value = "memberId",required = true)Long memberId,
                @RequestParam(value = "applyAmount",required = true)BigDecimal applyAmount,
                @RequestParam(value = "accountId",required = true)Long accountId,
                @Param("callback")String callback){
            try {
                walletService.applyWithdraw(memberId,applyAmount,accountId);
                AjaxUtils.renderJsonporJson(response,callback, ResultPageDOHelper.getMsgResultDOJx("成功"));
            }catch (Exception e){
                e.printStackTrace();
                AjaxUtils.renderJsonporJson(response,callback,ResultPageDOHelper.getMsgResultDOJx("失败"+e.getMessage()));
            }
        }

        /**
         * 获取提现记录
         */
        @RequestMapping(value = "/getWithDrawRecord",method = RequestMethod.POST)
        @ApiOperation(value = "【用户版和管理版】获取钱包余额提现记录。")
        public void getWithdraw(
                HttpServletRequest request,
                HttpServletResponse response,
                @RequestParam(value = "memberId",required = true)Long memberId,
                @Param("callback")String callback){
            try {
                Map<String,Object> param = ParamUtil.getParamInt(request,"memberId");
                PageResult<PearlWalletWithdrawRecord> result = walletService.getWithDrawRecord(request,memberId);
                AjaxUtils.renderJsonporJson(response,callback,ResultPageDOHelper.getResultPageDO(result.getTotal(),result.getData()));
            }catch (Exception e){
                e.printStackTrace();
                AjaxUtils.renderJsonporJson(response,callback,ResultPageDOHelper.getMsgResultDOJx("失败！")+e.getMessage());
            }
        }
    }